package App.Filter;

/**
 * Created by xw on 2018/11/16.
 */

import App.Model.BaseEnum;
import App.Model.BaseResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.catalina.security.SecurityConfig;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;


/*
* 用户没有登陆，访问API,提示没有登陆，不让访问API
* */
public class CustomAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

    Logger _log = Logger.getLogger("CustomAuthenticationEntryPoint");

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        BaseResponse _baseResponse = new BaseResponse();
        _baseResponse.setSuccess(BaseEnum.ApiResult.Failure.getApiResult());
        _baseResponse.setMessage("请先登录");

        OutputStream out = response.getOutputStream();
        com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(out, _baseResponse);
        out.flush();
    }

    @Override
    public void afterPropertiesSet() throws Exception {

        //为什么必须设置这个名字呢？
        setRealmName("lifa");
        super.afterPropertiesSet();
    }
}
